package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduorder.entity.TOrder;
import com.atguigu.eduorder.service.TOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author ct_start
 * @since 2021-08-24
 */
@RestController
@RequestMapping("/eduorder/order")
@CrossOrigin
public class TOrderController {

    @Autowired
    private TOrderService orderService;

    //1. 生成订单的方法,根据路径中传递的课程id  从请求头里面取出里面的token.登陆之后客户数据就已经存放在请求头里面了
    @PostMapping("createOrder/{courseId}")
    public R saveOrder(@PathVariable String courseId, HttpServletRequest request){

        // 还要解析 request 里面的信息,解析出里面的信息

        // 创建订单返回订单号

        String orderNo =orderService.createOrders(courseId, JwtUtils.getMemberIdByJwtToken(request));


        return  R.ok().data("orderId",orderNo);
    }


    // 2. 根据订单id 查询订单信息
    @GetMapping("getOrderInfo/{orderId}")
        public R getOrderInfo(@PathVariable String orderId){
        QueryWrapper<TOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_no",orderId);
        TOrder one = orderService.getOne(queryWrapper);

        return  R.ok().data("item",one);
    }

    // 根据课程和 用户id 查询订单表中订单的状态来判断是否被购买
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberId) {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1);//支付状态 1代表已经支付
        int count = orderService.count(wrapper);
        if(count>0) { //已经支付
            return true;
        } else {
            return false;
        }
    }

}

